//
//  YiLeftMenuView.swift
//  yiplayer
//
//  Created by wkun on 2024/6/7.
//

import UIKit

extension YiLeftMenuView {
    
    static func showLeftMenuView(_ inCtrl: UIViewController?, width: CGFloat, height: CGFloat) {
        let tag = 109091
        if let ic = inCtrl {
            var mv = ic.view.viewWithTag(tag) as? YiLeftMenuView
            if mv == nil {
                let w: CGFloat = 160.0//screenWidth*1/3+20.0
                mv = YiLeftMenuView.init(frame: .init(x: width, y: 0, width: w, height: height), inCtrl: ic, scrWidth: width)
                mv?.tag = tag
                
                mv?.showLeftMenuView()
            }
        }
    }
    
    static func hideLeftMenuView(_ inCtrl: UIViewController?) {
        let tag = 109091
        let mv = inCtrl?.view.viewWithTag(tag) as? YiLeftMenuView
        mv?.hideLeftMenuView()
    }
    
    
    func hideLeftMenuView() {
        
        var fr = self.frame
        UIView.animate(withDuration: self.animateTime) {
            fr.origin.x = self.scrWidth
            self.frame = fr
            self.effectView.alpha = 0
        } completion: { finish in
            
            //隐藏菜单后打开左滑手势
            self.effectView.removeFromSuperview()
            self.removeFromSuperview()
        }
    }
    
    func showLeftMenuView() {
        var fr = self.frame
        self.effectView.alpha = 0
        UIView.animate(withDuration: self.animateTime) {
            fr.origin.x = self.scrWidth-fr.size.width
            self.frame = fr
            self.effectView.alpha = 1
        } completion: { finish in
        }
    }
    
    // MARK: - 点击背景和左滑手势 隐藏菜单
    func setupGestureRecognizers(){
        
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(handleBg))
        effectView.addGestureRecognizer(tap)
        effectView.isUserInteractionEnabled = true
              
        let swipeLeftGesture = UISwipeGestureRecognizer.init(target: self, action: #selector(handleLeftSwipe(_:)))
        swipeLeftGesture.direction = .left
        self.effectView.addGestureRecognizer(swipeLeftGesture)
    }
    
    @objc func handleLeftSwipe(_ pan: UISwipeGestureRecognizer ) {
        
        self.hideLeftMenuView()
    }
    
    @objc func handleBg() {
        self.hideLeftMenuView()
    }
}


class YiLeftMenuView: UIView, UITableViewDelegate,UITableViewDataSource {

    var inCtrl: UIViewController?
    let tableView = UITableView()
    var datas: [MenuModel]?
            
    let animateTime = 0.3
    
    var effectView: TRLeftMenuMaskView!
    var scrWidth = 0.0
    
    init(frame: CGRect, inCtrl: UIViewController?, scrWidth: CGFloat) {
        super.init(frame: frame)
        
        self.inCtrl = inCtrl
        
        self.scrWidth = scrWidth
        
        effectView = TRLeftMenuMaskView(frame: CGRect(x: 0, y: 0, width: scrWidth, height: frame.height))
        
        self.setupGestureRecognizers()
        
        inCtrl?.view.addSubview(effectView)
        
        inCtrl?.view.addSubview(self)
        
        self.setupUI()
        self.loadDatas()
        
        let h = CGFloat(self.datas?.count ?? 0) * self.tableView.rowHeight
        
        let y = (frame.height-h)/2.0
        self.tableView.frame = .init(x: 0, y: y, width: frame.width, height:h)
        self.backgroundColor = .clear
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - LoadDatas
    func loadDatas() {
//        let imgs = ["m_charts","m_list","m_timelist","m_datacopy","m_export","m_set","m_help","m_about"]
        let imgs = ["home_album","home_files","home_net","home_zj","home_set"]
        let names = ["相册","文件","网络","最近","设置"]
//        let names = ["新建项目","目标列表","时间记录","时间类别","设置","帮助"]
        var arr = [MenuModel]()
        for i in 0..<names.count {
            let m = MenuModel()
            m.name = names[i]
            m.img = imgs[i]
            arr.append(m)
        }
        
        self.datas = arr
        self.tableView.reloadData()
    }
    
    // MARK: - Delegate
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.datas?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? MenuCell
        
        cell?.model = self.inCtrl?.model(datas, indexPath.row) as? MenuModel
         
        return cell ?? UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        if let c = self.inCtrl as? YiHomeCtrl {
            c.handleMenuItem(index: indexPath.row)
        }else if let c1 = self.inCtrl?.presentingViewController as? YiHomeCtrl {
            c1.handleMenuItem(index: indexPath.row)
        }
        
        self.hideLeftMenuView()
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        if cell.tag == 999 {
            return
        }
        
        //cell动画
        let rect = tableView .rectForRow(at: indexPath)
        cell.frame = .init(x: self.frame.width, y: cell.frame.minY, width: cell.frame.width, height: cell.frame.height)
        UIView.animate(withDuration: 0.3, delay: 0.1*Double(indexPath.row), options: .curveEaseInOut) {
            var fr = rect
//            fr.origin.y = fr.origin.y - 30
            fr.origin.x = fr.origin.x + 20
            cell.frame = fr
        } completion: { fini in
            UIView.animate(withDuration: 0.3) {
                cell.frame = rect
                
                cell.tag = 999
            }
        }
    }

    // MARK: - SetupUI
    func setupUI() {
        self.backgroundColor = .white

        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .clear
        tableView.separatorStyle = .none
        tableView.showsVerticalScrollIndicator = false
        tableView.addTo(self)
        tableView.register(MenuCell.self, forCellReuseIdentifier: "cell")
        tableView.frame = self.bounds
        //以下代码必须适配
        if #available(iOS 11, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        } else {
            
        }
        
        let hv = View
        hv.frame = .init(x: 0, y: 0, width: 10, height: 100)
        tableView.rowHeight = 55;
    }
    
    class MenuModel: NSObject{
        var name: String?
        var img: String?
    }
    
    class MenuCell: UITableViewCell {
        let imgView = UIImageView()
        let nameL = UILabel()
        let arrowView = UIImageView()
        
        var model: MenuModel? {
            didSet{
                imgView.image = UIImage.init(named: model?.img ?? "")?.withTintColor(ColorF)
                nameL.text = model?.name
            }
        }
        
        override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
            super.init(style: style, reuseIdentifier: reuseIdentifier)
            
            imgView.pin(.w(21)).mode(.scaleAspectFit)
            nameL.font(16).color(ColorF)
            
            HStack(imgView,20,nameL,NERSpring).embedIn(self.contentView,0,35,0,0).align(.center)
            
            arrowView.img("arrow_ani").pin(.wh(18, 18)).mode(.scaleAspectFit).addTo(self.contentView).makeCons { make in
                make.left.equal(0)
                make.centerY.equal(self.contentView).offset(0)
            }
            arrowView.isHidden = true
            
            self.contentView.backgroundColor = .clear
            self.backgroundColor = .clear
            self.selectedBackgroundView = nil
            self.selectionStyle = .none
        }
        
        required init?(coder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        
        override func layoutSubviews() {
            super.layoutSubviews()
            
//            self.getCellSelectedBgView().backgroundColor = .init(white: 0, alpha: 0.3)
        }
        
        override func setHighlighted(_ highlighted: Bool, animated: Bool) {
            super.setHighlighted(highlighted, animated: animated)
            
            let c = highlighted ? Color9 : ColorF
            self.nameL.textColor = c
            
            self.arrowView.isHidden = !highlighted
        }
    }
    
    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        let v = super.hitTest(point, with: event)
        if v == self {
            return nil;
        }
        return v
    }
}


class TRLeftMenuMaskView: UIView {
    var effectView: UIVisualEffectView?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        let blur = BLBlurEffect.getWith(.dark, blurRadius: 10.0) //
        
//        let blur = UIBlurEffect.init(style: .dark)
        effectView = UIVisualEffectView.init(effect: blur)
        effectView?.frame = .init(x: 0, y: 0, width: frame.width, height: frame.height)
        effectView?.alpha = 0.8
        self.addSubview(effectView!)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
